package org.mq.mymq.nameserver.store;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ServiceInstanceManager
 * @Description 服务实例管理类
 * @Author jiarong_ye
 * @Date 2025/6/19 14:33
 * @Version 1.0
 */
public class ServiceInstanceManager {
    private Map<String, ServiceInstance> serviceInstanceMap = new HashMap<>();

    public void put(ServiceInstance serviceInstance) {
        serviceInstanceMap.put(serviceInstance.getIp() + ":"
                        + serviceInstance.getPort(), serviceInstance);
    }

    public void putIfExist(ServiceInstance serviceInstance) {
        ServiceInstance currInstance = this.get(serviceInstance.getIp(), serviceInstance.getPort());
        if (currInstance != null && currInstance.getFirstRegistryTime() != null) {
            currInstance.setLastHeartBeatTime(serviceInstance.getLastHeartBeatTime());
        } else {
            throw new RuntimeException("heart beat cache miss, please register again");
        }
    }

    public ServiceInstance get(String brokerIp, Integer port) {
        return serviceInstanceMap.get(brokerIp + ":" + port);
    }

    public ServiceInstance get(String reqId) {
        return serviceInstanceMap.get(reqId);
    }

    public ServiceInstance remove(String key) {
        return serviceInstanceMap.remove(key);
    }

    public Map<String, ServiceInstance> getServiceInstanceMap() {
        return serviceInstanceMap;
    }

    public void reload(List<ServiceInstance> serviceInstanceList) {
        serviceInstanceMap.clear();
        serviceInstanceList.forEach(serviceInstance ->
            this.put(serviceInstance)
        );
    }
}
